package com.kevin.demo.service.base;


import com.github.pagehelper.Page;
import com.kevin.demo.dao.base.BaseDao;
import com.kevin.demo.enums.LogEnum;
import com.kevin.demo.framwork.LoggerUtil;
import com.kevin.demo.framwork.Result;
import com.kevin.demo.framwork.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author: e20160504
 * @date: 2018/7/20
 * @desc
 */
public class BaseService<T> {

    @Autowired
    private BaseDao<T> baseDao;

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    //获取运行时entity
    private Class<T> clazz = null;
    {
        Type type = getClass().getGenericSuperclass();
        if( type instanceof ParameterizedType){
            ParameterizedType pType = (ParameterizedType)type;
            Type claz = pType.getActualTypeArguments()[0];
            if( claz instanceof Class ){
                this.clazz = (Class<T>) claz;
            }
        }
    }

    //运行时entity的类名称
    public String getEntity(){
        try {
             return this.clazz.getSimpleName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
    *@params: 需要新增的entity
    *@return:
    *@desc: 新增一条记录
    */
    @Transactional
    public Result insert(T t) {
        LoggerUtil.info(logger,  getEntity() + LogEnum.ADD_START.getMsg());
        baseDao.insertSelective(t);
        return ResultUtils.success();
    }

    /**
    *@params: key
    *@return:
    *@desc:
    */
    @Transactional
    public Result delete(Object key) {
        LoggerUtil.info(logger, getEntity() + LogEnum.DEL_START.getMsg());
        Boolean flag = baseDao.deleteByPrimaryKey(key)==1?true:false;
        return ResultUtils.runtimeResult(flag);
    }

    /**
    *@params: 更新后的enttity
    *@return:
    *@desc: 根据主键更新一条记录
    */
    @Transactional
    public Result update(T obj) {
        LoggerUtil.info(logger, getEntity() + LogEnum.UPD_START.getMsg());
        int i = baseDao.updateByPrimaryKeySelective(obj);
        return ResultUtils.success();
    }

    /**
    *@params: 查询条件 带分页
    *@return:
    *@desc:  分页模糊查询
    */
    public Result list(Object filter) {
        LoggerUtil.info(logger, getEntity() + LogEnum.SEL_START.getMsg());
        Page<T> users =  baseDao.list(filter);
        return ResultUtils.successPage(users.getResult(), users.getTotal());
    }

    /**
    *@params: key
    *@return: entity
    *@desc:
    */
    public T selectByKey(Object id) {
        return baseDao.selectByPrimaryKey(id);
    }
}
